package com.vicene.gmail.product.exception;

import com.vicene.gmail.common.exception.CommonCodeEnum;
import com.vicene.gmail.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice(basePackages = "com.vicene.gmail.product.controller")
public class GmailExceptionControllerAdvice {

    //捕捉MethodArgumentNotValidException参数校验异常
    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public R handleVaildException(MethodArgumentNotValidException exception){
        log.error("数据校验出现问题:{},异常类型:{}",exception.getMessage() , exception.getClass());


        Map errorMap = new HashMap();
        BindingResult result = exception.getBindingResult();
        result.getFieldErrors().forEach((item) -> {
            String message = item.getDefaultMessage();
            String field = item.getField();
            errorMap.put(field, message);
        });
        return R.error(CommonCodeEnum.VALID_EXCEPTION.getCode(), CommonCodeEnum.VALID_EXCEPTION.getMsg()).put("data" , errorMap);
    }

    //其他捕捉Throwable
    @ExceptionHandler(value = Throwable.class)
    public R handleException(Throwable throwable){
        log.error("异常类型:{}",throwable);


        return R.error(CommonCodeEnum.UNKNOWN_EXCEPTION.getCode() ,CommonCodeEnum.UNKNOWN_EXCEPTION.getMsg() );
    }
}
